<?php
class common_model {
	protected $table;
	protected $prefix = DB_PREFIX;
	protected $pk;
	
	protected $sys_status_field='sys_status';
	protected $sys_created_field='sys_createdtime';
	protected $sys_updated_field='sys_stattime';
	
	protected  $_columns;
	/**
	 *
	 * @var c_common_mysql1
	 */
	protected $db;
	/**
	 * 构造函数
	 *
	 * @param array $data
	 */
	function __construct($data = array(),$table = null,$pk = null) {
		$table == null?'':$this->table = $table;
		$pk == null?'':$this->pk = $pk;
		$data?'':$this->_columns = $data;
		$this->db = new common_mysql();
	}
	/**
	 *
	 * @return c_common_mysql1
	 */
	function get_db(){
		return $this->db;
		
	}
	/**
	 * 析构函数
	 *
	 */
	function __destruct() {
		$this->db = null;
	}
	/**
	 * 初始化数据
	 * @param array
	 * @return array
	 */
	function init_data(array $data) {
		$out=array();
		foreach ($this->_get_columns() as $key =>$value) {
			$value;
			if (isset($data[$key])) {
				$out[$key] = $data[$key];
			}
		}
		return $out;
	}
	/**
	 * Create a record
	 * @param array $data
	 * @return mix
	 */
	function create(array $data) {
		$data=$this->init_data($data);
		if(array_key_exists($this->sys_created_field,$this->_get_columns())){
			$data[$this->sys_created_field]=time();
		}
		if(array_key_exists($this->sys_updated_field,$this->_get_columns())){
			$data[$this->sys_updated_field]=time();
		}
		if(
			array_key_exists(
				$this->sys_status_field,
				$this->_get_columns())
			&&!isset(
				$data[$this->sys_status_field])
		){
			$data[$this->sys_status_field]=0;
		}
		
		$keys=array_keys($data);
		foreach ($keys as &$key){
			$data[$key] = is_null($data[$key]) ? 'null' : "'".addslashes($data[$key])."'";
			$key="`$key`";
		}
		$sql = 'INSERT INTO `'
			.$this->prefix
			.$this->table
			.'` ('.join(',',$keys).') values'
			.'('.join(',',$data).')';
		$this->db->query($sql);
		return $this->db->insert_id();
	}
	/**
	 * 获得某条数据
	 *
	 * @return array
	 */
	function find($where, $order=null, $limit = null, $fields = '*'){
		$where = $this->_get_where_str($where);
		$sql = "SELECT $fields FROM {$this->prefix}{$this->table} WHERE $where";
		if($order) {
			$sql .=" ORDER BY $order ";
		}
		$sql .= $limit ? " LIMIT $limit " : ' LIMIT 1 ';
		return $this->db->fetch_row_query($sql);
	}
	
	/**
	 * 根据主键查找数据
	 *
	 * @param mix $pkv
	 * @return array
	 */
	function find_by_pk($pkv) {
		$pkv = c_arp::addslashes($pkv);
		$where = '';
		$where = is_array($pkv) ? "`{$this->pk}` IN (".c_arp::implode($pkv).')' : "`{$this->pk}`='{$pkv}' LIMIT 1";
		$sql="SELECT * FROM {$this->prefix}{$this->table} WHERE $where";
		return is_array($pkv) ? $this->db->fetch_query($sql) : $this->db->fetch_row_query($sql);
	}

	/**
	 * 
	 * 获取where语句
	 * @param array|string $condition
	 * @return string
	 */
	
	protected function _get_where_str($conditions){
		if(is_array($conditions)){
			$ps=array();
			$keys=array_keys($conditions);
			foreach($keys as $k){
				if(is_numeric($k)){
					$ps[] = $conditions[$k];
				}else{
					if(is_array($conditions[$k])){
						if(count($conditions[$k])>0){
							$inarr=array();
							foreach ($conditions[$k] as $it){
								$inarr[] = '"'.iaddslashes($it).'"';
							}
							$ps[] = "`$k` in (".join(',',$inarr).")";
							
						}else{
							$ps[] = '2=1';
						}
					}else{
						$ps[] = "`$k`="."'".iaddslashes($conditions[$k])."'";
					}
				}
			}
			return join(' AND ',$ps);
		}else{
			return $conditions;
		}
		
	} 
	
	/**
	 * 查询多条数据
	 *
	 * @param string|array $where
	 * @param string $order
	 * @param string $limit
	 * @param string $fields
	 * @return array
	 */
	function find_all($where , $order=null , $limit=null,$fields='*') {
		$where=$this->_get_where_str($where);
		$where = $where?"WHERE $where":'';
		$sql="SELECT $fields FROM {$this->prefix}{$this->table} $where";
		if($order){
			$sql .=" ORDER BY $order ";
		}
		if($limit){
			$sql .=" LIMIT $limit ";
		}
		return $this->db->fetch_query($sql);
	}
	/**
	 * 查询多条数据(主键作为返回值 的key)
	 *
	 * @param string|array $where
	 * @param string $order
	 * @param string $limit
	 * @param string $fields
	 * @return array
	 */
	function find_all_assoc($where, $order=null , $limit=null,$fields='*') {
		//$assoc_file = $assoc_file ? $assoc_file : $this->pk; 
		$result = array();
		$tmp_list = $this->find_all($where, $order, $limit,$fields);
		foreach ($tmp_list as $data){
			$result[$data[$this->pk]] = $data;
		}
		return $result;
	}
	/**
	 * 根据条件查询pkv list
	 */
	function get_pkv_list($where,$order=null,$limit=null){
		return $this->get_filed_values($this->pk,$where,$order,$limit);
	}
	/**
	 * 获取某个字段的数据列表
	 *
	 * @param string $field
	 * @param mix $where
	 * @param string $order
	 * @param string $limit
	 * @return array
	 */
	function get_filed_values($field,$where,$order=null,$limit=null){
		$l = array();
		$rs = $this->find_all($where,$order,$limit,$field);
		foreach($rs as &$r){
			$l[]=$r[$field];
		}
		return $l;
	}
	
	/**
	 * 计数
	 * @param string|array $where
	 * @return int
	 */
	function count_by_conditions($where){
		$where = $this->_get_where_str($where);
		$where = $where?"where $where":'';
		$sql="select count(1) as cnt  from {$this->prefix}{$this->table} $where";
		$result = $this->db->fetch_row_query($sql);
		return $result['cnt'];
	}
	/**
	 * 更新数据
	 * @param array $data
	 * @return boolean
	 */
	function update(array $data) {
		$data=$this->init_data($data);
		if(array_key_exists($this->sys_updated_field,$this->_get_columns())){
			$data[$this->sys_updated_field]=time();
		}
		$sql = 'UPDATE '.$this->prefix.$this->table.' SET ';
		foreach ($data as $key => $value) {
			if ($value !== null && $key != $this->pk) {
				$sql .= $key."='".addslashes($value)."',";
				// $sql .= $key."='".$value."',";
			}
		}
		$sql = substr($sql,0,-1).' where `'.$this->pk.'` ="'.$data[$this->pk].'"';
		return $this->db->query($sql);
	}
	/**
	 * update by condtions
	 *
	 * @param array $data
	 * @param mix $where
	 * @return boolean
	 */
	function update_by_conditions(array $data,$where){
		$data=$this->init_data($data);
		$where = $this->_get_where_str($where);
		if(array_key_exists($this->sys_updated_field,$this->_get_columns())){
			$data[$this->sys_updated_field]=time();
		}
		
		$sql = 'UPDATE '.$this->prefix.$this->table.' SET ';
		foreach ($data as $key => $value) {
			if ($value !== null && $key != $this->pk) {
				$sql .= $key."='".$value."',";
			}
		}
		$sql = substr($sql,0,-1).($where?' where '.$where:'');
		return $this->db->query($sql);
	}
	/**
	 * 虚拟删除
	 *
	 * @param mix $pk
	 * @return boolean
	 */
	function vitual_delete_by_pk($pk){
		if(!array_key_exists($this->sys_status_field,$this->_get_columns())){
			throw new Exception('sys_status_field dose not exist');
		}
		$data=array(
			$this->pk=>$pk,
			$this->sys_status_field=-1
		);
		return $this->update($data);
	}
	/**
	 * 删除数据
	 * @param mix $where
	 */
	function delete($where) {
		$where = $this->_get_where_str($where);
		$sql = 'delete from '.$this->prefix.$this->table;
		empty($where)?'':$sql .= ' where '.$where;
		return $this->db->query($sql);
	}
	/**
	 * 删除数据
	 * TODO修改了代码逻辑 相关调用待验证
	 */
	function delete_by_pk($pk) {
		$pk=addslashes($pk);
		$sql = 'delete from '.$this->prefix.$this->table.' where `'.$this->pk.'` = "'.$pk.'"';
		return $this->db->query($sql);
	}
	/**
	 * 执行sql语句
	 */
	function query($sql) {
		return $this->db->query($sql);
	}
	function query_db($sql) {
		return $this->db->fetch_query($sql);
	}
	public function _get_columns(){
		if(!$this->_columns){
			$sql='SHOW FULL COLUMNS FROM '.$this->prefix.$this->table;
			$cs=$this->db->fetch_query($sql);
			foreach ($cs as $c){
				$this->_columns[$c['Field']]=null;
			}
		}
		return $this->_columns;
	}
}
?>